package thread;

import thread.biz.DOrder;
import thread.biz.Diff;
import thread.biz.POrder;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * st.test.juc.p01
 *
 * @description: CmpletableFuture方式
 * @author: yechen
 * @email: wangqingfeng@wxyundian.com
 * @date: 2019年09月27日 11:34
 */
public class CheckBatch4 extends AbstractCheckBatch {

    @Override
    public void doProcess() throws Exception {
        System.out.println("---- CmpletableFuture处理 ----");
        //服务器端最佳线程数量=((线程等待时间+线程cpu时间)/线程cpu时间) * cpu数量
        ExecutorService executor = Executors.newFixedThreadPool(100);
        ExecutorService executor1 = Executors.newFixedThreadPool(100);

        List<CompletableFuture<Integer>> futureList = ids.stream().map(id -> CompletableFuture.supplyAsync(() -> check(id, executor1), executor))
                .collect(Collectors.toList());
        futureList.stream().map(CompletableFuture::join).collect(Collectors.toList());
        //关闭执行服务对象
        executor.shutdown();
        executor1.shutdown();
    }

    public Integer check(Integer id, ExecutorService executor) {
        CompletableFuture<POrder> f1 = CompletableFuture.supplyAsync(() -> pOrderService.getPOrder(id), executor);
        CompletableFuture<DOrder> f2 = CompletableFuture.supplyAsync(() -> dOrderService.getDOrder(id), executor);
        try {
            POrder pOrder = f1.get();
            DOrder dOrder = f2.get();
            Diff diff = check(pOrder, dOrder);
            if (diff != null)
                // 2ms
                save(diff);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        return 1;
    }


    @Override
    protected void doFinal() {

    }
}
